package com.wu.util.spider.service.impl;

import com.wu.util.spider.entity.RecordBaseEntity;
import com.wu.util.spider.service.BaseSpiderWorkerService;
import com.wu.util.spider.util.SpiderConfiguration;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;


/**
 * @author 50816
 */
@Service("xiGuaVideoServiceWorkerImpl")
public class XiGuaVideoServiceWorkerImpl extends BaseSpiderWorkerService {

    Logger logger = LoggerFactory.getLogger(XiGuaVideoServiceWorkerImpl.class);

    private static final Integer FULL_LIMIT = 36;

    @Autowired
    SpiderConfiguration spiderConfiguration;

    @Autowired
    @Qualifier("xiGuaDisposeServiceImpl")
    XiGuaDisposeServiceImpl disposeService;

    @Override
    public void startService() {
        int pageNum = 1;

        while (true) {
            URI url = null;
            try {
                url = new URI(spiderConfiguration.getBaseUrl() + "/fenlei/id5-" + pageNum + ".html");
                CloseableHttpResponse response = HTTP_CLIENT.execute(getRequestMethod(url));
                if (response.getStatusLine().getStatusCode() != 200) {
                    break;
                }
                String document = EntityUtils.toString(response.getEntity(), "UTF-8");
                if (resolvingDocument(document)) {
                    break;
                }
            } catch (URISyntaxException | IOException e) {
                logger.error("解析西瓜视频网址:{}异常:{}", url.getPath(), e.getMessage(), e);
            }
            pageNum += 1;
            try {
                Thread.sleep(1000 * spiderConfiguration.getSleepTime());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 解析html内容
     * <p>
     * li class="col-lg-6  col-md-6 col-sm-4 col-xs-3">
     * <div class="myui-vodlist__box"> <a class="myui-vodlist__thumb lazyload" href="/movie/info91486.html" title="止杀令" data-original="/uploads/allimg/201125/6e9575e82a560729.jpg" target="info"> <span class="play hidden-xs"></span> <span class="pic-tag pic-tag-top" style="background-color: #5bb7fe;"> 9.0 </span> <span class="pic-text text-right"> HD </span> </a>
     *  <div class="myui-vodlist__detail">
     *   <h4 class="title text-overflow"><a href="/movie/info91486.html" title="止杀令" target="info">止杀令</a></h4>
     *   <p class="text text-overflow text-muted hidden-xs"> 主演：赵有亮 / 涂们 / 李小冉 / 耿乐 / 余少群 / 中泉英雄 / 朴艺珍 / 徐锦江 </p>
     *  </div>
     * </div> </li>
     *
     * @param document html
     * @return 是否到最后一页 true 结束 false 继续
     */
    private Boolean resolvingDocument(String document) throws URISyntaxException, IOException {
        Element body = Jsoup.parse(document).body();
        Elements array = body.select(".myui-vodlist").select("li");
        for (Element item : array) {
            Elements element = item.select(".myui-vodlist__thumb");
            String imgPath = element.attr("data-original");
            String pagePath = element.attr("href");
            String resourceName = element.attr("title");
            disposeService.saveImage(spiderConfiguration.getBaseUrl() + imgPath, resourceName + ".jpg");
            URI uri = new URI(spiderConfiguration.getBaseUrl() + pagePath);
            HttpRequestBase requestMethod = this.getRequestMethod(uri);
            //请求详情页面
            CloseableHttpResponse response = HTTP_CLIENT.execute(requestMethod);
            if (response.getStatusLine().getStatusCode() != 200) {
                break;
            }
            String detailPage = EntityUtils.toString(response.getEntity(), "UTF-8");
            RecordBaseEntity recordBaseEntity = new RecordBaseEntity();
            recordBaseEntity.setImage(spiderConfiguration.getBaseUrl() + imgPath);
            disposeService.resolvingDetail(detailPage, recordBaseEntity);
        }
        return array.size() < FULL_LIMIT;
    }


}
